import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '@/store';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

import Layout from '@/layout';

Vue.use(VueRouter);

// 静态路由(公共)
export const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login.vue'),
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/error/404'),
  },
  {
    path: '/',
    component: Layout,
    redirect: '/backstage/home',
    children: [
      {
        path: '/backstage/home',
        component: () => import('@/views/index'),
        name: 'Home',
      },
    ],
  },
  {
    path: '/user',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '/backstage/profile',
        component: () => import('@/views/user/profile/index'),
        name: 'Profile',
      },
    ],
  },
];

// 动态路由，基于用户权限动态去加载
export const asyncRoutes = [
  {
    path: '/backstage/product',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Product',
        component: () => import('@/views/test/index'),
      },
      // {
      //   path: '/backstage/template/detail',
      //   name: 'Detail',
      //   component: () => import('@/views/equip/template/detail.vue'),
      // },
    ],
  },
  // 跳转页面路由
  // {
  //   path: '/404',
  //   isPage: true,
  //   component: () => import('@/views/test/index'),
  //   name: 'Product',
  //   children: [],
  // },
];

const createRouter = () =>
  new VueRouter({
    // mode: 'history', // require service support
    mode: 'history', // 路由模式 默认是hash
    scrollBehavior: () => ({ y: 0 }), // 路由的滚动行为
    routes: [...constantRoutes],
  });

const router = createRouter(); // 每次调用都会拿到一个新的router实例对象

// 这个方法就是用来重置路由的方法 只要调用此方法就可以把先前的路由记录清空
export function resetRouter() {
  // 得到一个全新的router实例对象
  const newRouter = createRouter();

  // 使用新的路由记录覆盖掉老的路由记录
  // 包含了所有的路由记录 path - component
  router.matcher = newRouter.matcher; // reset router
}

// 路由前置守卫
// 白名单
const WHITELIST = ['/login', '/404'];
router.beforeEach(async (to, from, next) => {
  NProgress.start(); // 开启进度条

  const token = window.sessionStorage.getItem('token');

  if (token) {
    // 有token
    if (to.path === '/login') {
      next('/');
    } else {
      // next();
      // 最合适的位置 满足以上三个条件 调用action函数
      // 如果当前已经调用过了 vuex已经存在数据 就不需要重复调用
      if (!store.state.user.id) {
        // 获取用户信息的接口
        store.commit('LOADING_HANDLER', true);
        store.dispatch('GetInfo').then(() => {
          store.dispatch('GetMenu').then((menuPermission) => {
            const filterRoutes = asyncRoutes.filter((route) =>
              menuPermission.includes(
                route.children.length != 0 ? route.children[0].name : route.name
              )
            );
            let routeConfig = [
              ...filterRoutes,
              { path: '*', redirect: '/404' },
            ];
            store.commit('SET_ROUTE', routeConfig);
            routeConfig.forEach((route) => {
              router.addRoute(route);
            });
            next({ ...to, replace: true });
            store.commit('LOADING_HANDLER', false);
          });
        });
      } else {
        next();
      }
    }
  } else {
    // 没有token
    if (WHITELIST.includes(to.path)) {
      next();
    } else {
      next('/login');
    }
  }
  NProgress.done();
});

// 防止连续点击多次路由报错
let routerPush = VueRouter.prototype.push;
let routerReplace = VueRouter.prototype.replace;
// push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch((err) => err);
};
// replace
VueRouter.prototype.replace = function push(location) {
  return routerReplace.call(this, location).catch((err) => err);
};

export default router;
